<template>
  <div class="news-list">
    <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
    >
      <div v-for="news in newsList" :key="news.id" class="news-item" @click="goToDetail(news)">
        <img :src="news.coverImage" class="news-cover" />
        <div class="news-content">
          <h3 class="news-title">{{ news.title }}</h3>
          <div class="news-meta">
            <span>{{ news.author }}</span>
            <span>{{ formatTime(news.createTime) }}</span>
          </div>
        </div>
      </div>
    </van-list>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from '../utils/axios.ts'

const router = useRouter()
const newsList = ref([])
const loading = ref(false)
const finished = ref(false)

const onLoad = async () => {
  if (loading.value) return
  loading.value = true

  try {
    // 模拟新闻数据，因为没有实际的API
    const mockNews = [
      {
        id: 1,
        title: "唐舞桐建模进化史：5大建模一次看够",
        coverImage: "https://img.yzcdn.cn/vant/cat.jpeg",
        content: "绝世唐门女主多次变换身份，从最初的青涩少女到后来的成熟女神，她的建模也在不断进化。",
        createTime: "2025-09-12T10:07:49",
        author: "云漫菌"
      },
      {
        id: 2,
        title: "斗罗大陆新剧情爆料",
        coverImage: "https://img.yzcdn.cn/vant/cat.jpeg",
        content: "最新剧情中，唐三将面临前所未有的挑战，而小舞的回归也将带来新的变数。",
        createTime: "2025-09-10T14:30:00",
        author: "动漫前线"
      }
    ];
    newsList.value.push(...mockNews);

    // 如果有实际API，使用下面的代码
    // const res = await axios.get('/api/news/list')
    // const data = res.data
    // newsList.value.push(...data)
  } catch (error) {
    console.error('加载新闻失败:', error)
  } finally {
    loading.value = false
    finished.value = newsList.value.length >= 10 // 模拟分页
  }
}

const goToDetail = (news) => {
  // 修复路由跳转方式，使用params而不是query
  router.push({ name: 'newsDetail', params: { id: news.id } })
}

const formatTime = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleDateString()
}

onMounted(() => {
  onLoad()
})
</script>

<style scoped>
.news-list {
  background-color: #f7f8fa;
}
.news-item {
  display: flex;
  padding: 16px;
  background: white;
  margin-bottom: 10px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}
.news-cover {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}
.news-content {
  flex: 1;
  margin-left: 12px;
}
.news-title {
  font-size: 16px;
  margin: 0 0 8px 0;
  line-height: 1.4;
}
.news-meta {
  font-size: 12px;
  color: #999;
}
</style>
